function [Fitted_Curve Est] = fitPolicy(d, deltaT, Bound)

if nargin <= 1
    deltaT = 9.5017 * 0.001;
    Bound = 48.6;
end

starting = [8 0.5];
options = '';
phi =  d(:,2) ./ (1:length(d(:,2)))';

win = 1;
phi(win+1:end-win) = conv(phi, ones(2* win + 1,1)/(2 *win + 1), 'valid');
nT = length(phi);
x = (1: nT)';
phi2 = phi(phi<1);
x2 = x(1:length(phi2));
Est = fminsearch(@fitinv, starting, options, x2, phi2);
Fitted_Curve =  1 - Est(2) * x2 ./ (x2 +  Est(1));
Fitted_Curve = [ones(sum(phi>=1),1); Fitted_Curve];


figure;
hold off;
plot(deltaT * x, Bound * (1 - phi) * 2,'ro-');
hold on;
plot(deltaT * x, Bound *  (1 - Fitted_Curve) * 2);
xlim([0, 2]);
ylim([0 Bound]);
xlabel('Time t (s)', 'FontWeight', 'bold','FontSize',30);
ylabel('Policy \pi', 'FontWeight', 'bold','FontSize',30);
hleg = legend('Optimal \phi',sprintf('t_{1/2} = %.3f', deltaT * (Est(1) + sum(phi>=1))),'Location','SouthEast');
set(hleg, 'FontWeight', 'bold','FontSize',30);
set(gca,  'LineWidth',2,...
    'FontWeight','bold');
set(gcf,'paperunits','inches');
set(gcf,'papersize',[12 18]);
set(gcf,'paperposition',[0,0,12,18]);
saveas(gcf, 'decisionBoundary.jpg','jpg');
saveas(gcf, 'decisionBoundary.fig','fig');


function sse=fitinv(params,x,y)
tau=params(1);
A = params(2);
Fitted_Curve=   1 - A * x ./(x + tau);
Error_Vector = Fitted_Curve - y;
% When curvefitting, a typical quantity to
% minimize is the sum of squares error
% You could also write sse as
% sse=Error_Vector(:)'*Error_Vector(:);
sse=sum(Error_Vector.^2);

